package com.ruoci.redis.cachebreakdown;

import com.ruoci.redis.constants.BusinessConstants;
import com.ruoci.redis.entity.Users;
import com.ruoci.redis.response.BasicResponse;
import com.ruoci.redis.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;

/**
 * @Author yang
 * 缓存击穿(Redis中数据过期导致一瞬间大量请求直接访问MySQL)
 **/
@Slf4j
@RestController
@RequestMapping("/breakdown")
public class BreakdownController {


    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UsersService usersService;

    @GetMapping("/cache")
    public BasicResponse breakdown(){
        Object obj = redisTemplate.opsForValue().get(BusinessConstants.USER_DATA);
        if (obj == null){
            synchronized (this){
                obj = redisTemplate.opsForValue().get(BusinessConstants.USER_DATA);
                if(obj != null){
                    return BasicResponse.success(obj);
                }
                log.info("查询数据库数据放入缓存.......");
                List<Users> list = usersService.list();
                redisTemplate.opsForValue().set(BusinessConstants.USER_DATA,list, Duration.ofHours(2L));
                return BasicResponse.success(list);
            }
        }else {
            return BasicResponse.success(obj);
        }
    }
}
